package com.leyou.user.controller;

import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 数据校验
     * @param data 数据
     * @param type 1：用户名 2：手机号码
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean>  checkData(@PathVariable("data")String data,
                                              @PathVariable("type")Integer type){
        return ResponseEntity.ok(userService.checkData(data,type));
    }

    /**
     * 验证码校验
     * @param phone  手机号码参数
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 注册用户
     * @param user  用户信息：用户名、用户密码、手机号
     * @param code  验证码信息
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            String msg = allErrors.stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400,msg);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username  用户名
     * @param password  密码
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<UserDTO> queryByUsernameAndPassword(@RequestParam("username") String username,
                                                              @RequestParam("password") String password){
        UserDTO ud = userService.queryUserByUsernameAndPassword(username, password);
        return ResponseEntity.ok(ud);
    }

}
